﻿<?php
set_time_limit(0);
class Wbtools extends CI_Controller
{
    public $data = array();
    function __construct() {
        parent::__construct();
        $this->load->helper('url');
        $this->config->load('siteset',true);
        $this->data['siteset'] = $this->config->item('siteset');
        $params = array('client_id' => $this->data['siteset']['client_id'], 
            'client_secret' => $this->data['siteset']['client_secret'],
             'access_token' => '',
             'refresh_token' => $this->data['siteset']['refresh_token'],
             );
         $this->load->library('Sinaapi',$params);
    }
    public function checkpay()
    {
        $DB1 = $this->load->database('update', TRUE);
        $isok = false;
        $newchktime = $this->data['siteset']['chktime'];
        $repost_time = $this->data['siteset']['jyilimit'];
        $newchktime = time() - ($newchktime*3600);
        $repost_ntime = time() - ($repost_time*3600);
        $this->db->where('(datatime < '.$newchktime.' and ptype=1)');
        $this->db->or_where('(datatime < '.$repost_ntime.' and ptype=2)');
        
        //$this->db->where_or('datatime <',$newchktime);
        $query = $this->db->get('wtt_chkpay');
        if($query->num_rows()>0)
        {
            $this->load->model('Mwbuser');
            
            foreach ($query->result_array() as $row) {
                $isok = false;
                $uinfo = $this->Mwbuser->getinfo($row['uid'],'access_token,screen_name');
                if(!empty($uinfo)){ 
                    $this->sinaapi->access_token = $uinfo['access_token'];
                    if($row['ptype'] == 1){
                    $r_info = $this->_chkfollows($row['uid'],$row['touid']);
                    if($r_info == '1'){
                        $isok = TRUE; 
                    }
                    }elseif($row['ptype']=='2'){
                        $r_info = $this->_chkrepost($row['uid'],$row['mid'],$row['touid']);
                        if($r_info == '1'){
                        $isok = TRUE; 
                        }
                    }
                //
                    if($isok == TRUE)
                    {
                        $uid = $row['uid'];
                        $touid = $row['touid'];
                        $points = $row['points'];
                        $this->Mwbuser->setjifen($uid,$points,2);
                        $this->Mwbuser->insertlog($uid,$touid,$uinfo['screen_name'],6,$points,2,$row['ptype']);
                        $this->Mwbuser->setjifen($touid,$points,1);
                        $uinfos = $this->Mwbuser->getinfo($row['touid'],'screen_name');
                        if(empty($uinfos)) $uinfos['screen_name']='';
                        $this->Mwbuser->insertlog($touid,$uid,$uinfos['screen_name'],7,$points,1,$row['ptype']);
                    }
                    $isok = FALSE;
                    if($r_info != '3')
                    {
                        $DB1->where('uid',$row['uid']);
                        $DB1->where('touid',$row['touid']);
                        $DB1->where('datatime',$row['datatime']);
                        $DB1->delete('wtt_chkpay'); 
                     }
                }
               //sleep(2); 
            }
        }
    }
    
     //检测邀请好友
	 
    public function chktuijian()
    {
        $DB1 = $this->load->database('update', TRUE);
        $chktime = (time() - 6*3600);
        $this->db->from('wtt_tuijian');
        $this->db->where('datatime <',$chktime);
        $query = $this->db->get();
        if($query->num_rows() > 0)
        {
            $this->load->model('Mwbuser');
            foreach($query->result_array() as $row)
            {
              $this->db->from('wtt_pays');
              $this->db->where('types !=',4);
              $this->db->where('uid',$row['uid']);
              $this->db->where('types !=',0);
              if($this->db->count_all_results()> 0)
              {
                $this->Mwbuser->tuijians($row['uid'],$this->data['siteset']['yaojifen']);
              }else{
                $DB1->delete('wtt_tuijian',array('uid'=>$row['uid']));
              }

            }
        }
    }
    
    //返回积分操作
    
    function givejifen()
    {
        $DB1 = $this->load->database('update', TRUE); 
        $query = $this->db->get_where('wtt_pays',array('types'=>7));
         foreach($query->result_array() as $row)
         {
             $DB1->query('update wtt_customers set jifen=jifen-'.$row['points'].' where wb_id='.$row['uid']); 
             $DB1->query('DELETE FROM wtt_pays where id='.$row['id'].' and uid='.$row['uid'].' and touid='.$row['touid'].' and datatime='.$row['datatime'].' and types='.$row['types'].' '); 
         }
         echo 'ok!';
    }

    //自动关注和转发
    function autopay()
    {
        $DB1 = $this->load->database('update', TRUE);
        //bingin 自动转发
        
        $this->db->select("a.wb_id,a.isgood,b.gender,b.followers_count,b.access_token,b.screen_name");
        $this->db->from('wtt_autos as a');
        $this->db->join('wtt_customers b','a.wb_id = b.wb_id','left');
        $this->db->where("(a.r_uptime+a.r_limit*60)<=".time()." and a.israuto=1 and b.status=0");
        $this->db->order_by('a.isgood','desc');
        $query = $this->db->get();
        if($query->num_rows()>0)
        {
            
            $this->load->model('Mfollow');
            foreach ($query->result_array() as $item) 
            {
                $getfs = $this->Mfollow->reposttuis($item,1,0,0,1);
                if(is_array($getfs) && !empty($getfs)){
                    
                    $arr['info'] = $this->Mfollow->dorepost($item['wb_id'],$getfs[0]['id'],'',0,$this->data['siteset']['r_h_limit'],$this->data['siteset']['r_d_limit']); 
                    if(empty($arr['info'])){
                        $toinfo = $this->Mfollow->get($getfs[0]['id'],1);
                        if(empty($toinfo)) $arr['info'] = '获取推广列表错误';
                        $rp_points = $toinfo['rp_points'];
                        $touid = $toinfo['uid'];
                        $wb_cid =  $toinfo['status_id'];
						
						$p_nkn = $this->Mwbuser->getinfo($toinfo['uid'],'screen_name');
                        $z_li_y = '//@'.$p_nkn['screen_name']."：".$toinfo['wb_text'];
                        if(empty($toinfo['r_text']))
                        {
                            $rand_arr = array('转发微博','转发微博','转发微博','转发微博','转发微博','分享转发','支持转起[威武]','扩散一下[给力]','转发了~~必须支持','来打酱油的','好内容值得推荐','[哈哈]','[话筒]','[浮云]','转发微博','转发微博','转发微博','转发微博','转发微博','转发微博','转发微博','转发微博','转发微博','是这样子的吗','原来如此~[good]','额。这…','就是这么回事','转发微博',' ','','');
                            //$this->load->model('Mwbuser');
                            //$p_nkn = $this->Mwbuser->getinfo($toinfo['uid'],'screen_name');
                            //如果更改上面数组的个数，请相应更改下面的参数个数，数组总长度减1
                            $z_li_y = $rand_arr[rand(0,30)];
                        }
                        $this->sinaapi->access_token = $item['access_token'];
						
						//这个是转发函数 三个参数第一个是转发微博的id ,2个是评论内容,3个是否评论，1是评论，0是不评论。
						$wb_c = $this->sinaapi->repost($toinfo['status_id'],$z_li_y,0);
						
                        //echo $wb_c['error'];
                        if(isset($wb_c['error']) || !empty($wb_c['error'])){
						
						 	if($wb_c['error_code'] == '20101' || $wb_c['error_code'] =='20120'){
							// 遇到微博不存在或可见性直接删除推广
							 	$this->Mfollow->deleteg($touid,$getfs[0]['id'],1);
								
							}else if($wb_c['error_code'] == '21327' || $wb_c['error_code'] =='21332' || $wb_c['error_code'] =='10013' || $wb_c['error_code'] =='20003' || $wb_c['error_code'] =='20501' || $wb_c['error_code'] =='21315'){
								$this->db->query("update wtt_autos set israuto=0 where wb_id='".$item['wb_id']."'");//关闭自动转发
							}else{
								//log_message('error', $wb_c['error_code']);
								// $this->Mfollow->setactive($touid,$getfs[0]['id'],1,0);
							}
						
                         }else{
                            $this->load->model('Mwbuser');
                            $toinfo = $this->Mwbuser->setjifen($touid,$rp_points,2);
                            $this->Mfollow->setnum($getfs[0]['id'],1);
                            $toinfo = $this->Mwbuser->setjifen($item['wb_id'],($rp_points-1),1); 
                            $this->Mwbuser->insertlog($item['wb_id'],$touid,$item['screen_name'],2,$rp_points);
                            $this->Mwbuser->insetchkpay($item['wb_id'],$touid,$getfs[0]['id'],$wb_c['mid'],2,$rp_points);
                            $DB1->query("update wtt_autos set r_uptime=".time()." where wb_id='".$item['wb_id']."'");   
                         }
                       
                    }
                }
				sleep(0.6);
            }
        }

        //end 
        //begin 自动关注
	//一次全部关闭自动关注	
	//$DB1->query("update wtt_autos set isfauto=0");
	//end
         $this->db->select("a.wb_id,b.gender,b.followers_count,b.access_token,b.screen_name");
        $this->db->from('wtt_autos as a');
         $this->db->join('wtt_customers b','a.wb_id = b.wb_id','left');
         $this->db->where("(a.f_uptime+a.f_limit*60)<=".time()." and a.isfauto=1 and b.status=0");
         $query = $this->db->get();
        if($query->num_rows()>0)
        {
            
            $this->load->model('Mfollow');
            foreach ($query->result_array() as $item) {
                $getfs = $this->Mfollow->followtuis($item,1,0,0,1);
                if(!empty($getfs)){
                    $touid = $getfs[0]['uid'];    
                    $arr['info'] = $this->Mfollow->dofollow($item['wb_id'],$getfs[0]['uid'],$this->data['siteset']['f_h_limit'],$this->data['siteset']['f_d_limit']);
                     if(empty($arr['info'])){
                         $this->sinaapi->access_token = $item['access_token'];
                         $wb_c = $this->sinaapi->follow_by_id($getfs[0]['uid']);
                         $touid = $getfs[0]['uid'];
                        // echo $wb_c['error'];
                          if(isset($wb_c['error']) || !empty($wb_c['error'])){
                            //如果授权过期、关注上限，自动赚分设置为关闭状态
                            if($wb_c['error_code'] =='21332' || $wb_c['error_code'] =='21315' || $wb_c['error_code'] =='21327' || $wb_c['error_code'] =='20513' || $wb_c['error_code'] =='10013' || $wb_c['error_code'] =='10023'){
							$DB1->query("update wtt_autos set isfauto=0 where wb_id='".$item['wb_id']."'");
			
                            }else{                      
                                //写入已经关注的例外信息
                                $this->Mfollow->insert_hasfls($item['wb_id'],$touid);
                            }
                         }else{
                            $toinfo = $this->Mfollow->get($touid);
                            $xjif = $toinfo['follow_points'];
                            $toinfo = $this->Mwbuser->setjifen($touid,$xjif,2);
                            $this->Mfollow->setnum($touid,0);
                            $toinfo = $this->Mwbuser->setjifen($item['wb_id'],($xjif-1),1);
                            $this->Mwbuser->insertlog($item['wb_id'],$touid, $item['screen_name'],1,$xjif);
                            $this->Mwbuser->insetchkpay($item['wb_id'],$touid,0,0,1,$xjif);
                
                        }
                       $DB1->query("update wtt_autos set f_uptime=".time()." where wb_id='".$item['wb_id']."'"); 
                     }
                }
                sleep(1.2);
            }
            
        }
        //end 自动关注
        
    }
    
	//关注：1违规，2正常，3是下次重新检查
    private function _chkfollows($uid,$touid)
    {
        //$this->sinaapi->debug = true;
        $r_info = $this->sinaapi->is_followed_by_id($touid,$uid);
       
        if(isset($r_info['error_code']))
        {
            //log_message('error', $r_info['error_code']);
			  if($r_info['error_code'] == '20501'  || $r_info['error_code'] == '21327' || $r_info['error_code'] == '21315' || $r_info['error_code'] == '20003' || $r_info['error_code'] == '10013' || $r_info['error_code'] == '21332' || $r_info['error_code'] == '21319') //错误是用户不存在
							{
							//求转发$this->db->query('update wtt_repost set rp_status=0 where uid='.$uid);
							//求关注$this->db->query('update wtt_follow set follow_status=0 where uid='.$uid);
							//自动赚分关闭$this->db->query('update wtt_autos set isfauto=0,israuto=0 where wb_id='.$uid);
							return 2;//不算违规
							 }else{
							  return 1;
							}
											
            //if($r_info['error_code'] =='20501') return 2;原
            //if($r_info['error_code'] =='21327') return 2;
            //if($r_info['error_code'] =='21315') return 2;
			//if($r_info['error_code'] =='20003') return 2;
            //if($r_info['error_code'] =='10013') return 2;
            //return 1;原
        }else{
             //print_r(($r_info));
             //echo $r_info['source']['followed_by'];
               // exit;
            if($r_info['source']['following'] == true)
            {
               // echo 'sssss';
                //exit;
                return 2;
            }else{
               // echo 'bbbbb';
               // exit;
                return 1;
            }
        }
        
    }
    
    function chklog()
    {
        $this->sinaapi->access_token = '2.003k1HIDc4LpED76668d151foMQtBC';
        $r_info = $this->sinaapi->show_status('3479107222335296');
        print_r($r_info);
    }
    function chklogs()
    {
        
        $uid = $this->input->get('uid');
        $touid= $this->input->get('touid');
        if(!is_numeric($touid) || !is_numeric($uid)){
            $r_info = '参数错误2！';
        }
        
        if(empty($r_info)){
            $this->load->model('Mwbuser');
            $uinfo = $this->Mwbuser->getinfo($uid,'access_token,screen_name');
            if(!empty($uinfo)){ 
                $this->sinaapi->access_token = $uinfo['access_token'];
                $r_info = $this->sinaapi->is_followed_by_id($touid,$uid);
            }else{
                $r_info = '参数错3误！';
            }
        
        }
        header("content-type: text/html; charset=utf-8");
        print_r($r_info);
    }
    private function _chkrepost($uid,$mid,$touid)
    {
        //$this->sinaapi->debug = true;
		//转发：违规1，正常2，下次检测3
        $r_info = $this->sinaapi->show_status($mid);
       
        if(isset($r_info['error_code']))//获取微博有错
        {
		   //$this->_writelog($this->JSON($r_info));
           // $err_arr = array('20101','20102','21332','21327','21315');
           //if(in_array($r_info['error_code'],$err_arr)) return 1;
		   //log_message('error', $r_info['error_code']);
					    if($r_info['error_code'] =='20101') //微博不存在时
					    {
					          $this->load->model('Mwbuser');
						      $wb_info = $this->Mwbuser->getinfo($uid,'access_token');
					          $this->sinaapi->access_token =$wb_info['access_token'];
					          $wb_info = $this->sinaapi->show_user_by_id($uid);
					         // if(!is_array($wb_info) && isset($wb_info['error']) )//链接用户有错误时，
							 // {
										  if($wb_info['error_code'] == '20003'  || $wb_info['error_code'] == '21327' || $wb_info['error_code'] == '21315' || $wb_info['error_code'] == '10013' || $wb_info['error_code'] == '20501' || $wb_info['error_code'] == '21332' || $wb_info['error_code'] == '21319') //错误是用户不存在
										  {
											$this->db->query('update wtt_repost set rp_status=0 where uid='.$uid);
											$this->db->query('update wtt_follow set follow_status=0 where uid='.$uid);
											$this->db->query('update wtt_autos set isfauto=0,israuto=0 where wb_id='.$uid);
											return 2;//不算违规
										  }else{
											return 1;//账户正常算违规
										  }
						    // }else{//如果微博不存在，且用户能链接则违规
						    //    return 1;
						    // }
					     }
		   //if($r_info['error_code'] =='20101') return 1;
		   //if($r_info['error_code'] =='21332') return 1;
           return 2;  
        }else{
           if($uid != $r_info['user']['id']) return 1;
           if(!isset($r_info['retweeted_status'])) 
           {
               return 1;
           }
            return 2; 
        }
    }
    
    private function _writelog($logs)
    {
        $this->load->helper('file');
        write_file('E:\wwwroot\hufen\tt_app\logs\\'.date('Y-n-j', time()).'.txt', $logs.'\r\n','a');
	return true;	
    }
    
    /**************************************************************
 *
 *	使用特定function对数组中所有元素做处理
 *	@param	string	&$array		要处理的字符串
 *	@param	string	$function	要执行的函数
 *	@return boolean	$apply_to_keys_also		是否也应用到key上
 *	@access public
 *
 *************************************************************/
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
    static $recursive_counter = 0;
    if (++$recursive_counter > 1000) {
        die('possible deep recursion attack');
    }
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $this->arrayRecursive($array[$key], $function, $apply_to_keys_also);
        } else {
            $array[$key] = $function($value);
        }
 
        if ($apply_to_keys_also && is_string($key)) {
            $new_key = $function($key);
            if ($new_key != $key) {
                $array[$new_key] = $array[$key];
                unset($array[$key]);
            }
        }
    }
    $recursive_counter--;
}
 
/**************************************************************
 *
 *	将数组转换为JSON字符串（兼容中文）
 *	@param	array	$array		要转换的数组
 *	@return string		转换得到的json字符串
 *	@access public
 *
 *************************************************************/
function JSON($array) {
    $this->arrayRecursive($array, 'urlencode', true);
	$json = json_encode($array);
	return urldecode($json);
}


}
